package nancal.mp.mvc


import nancal.mp.client.api
import nancal.mp.config.base.MyGatewayRouteRepository
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.log.StopLog
import nbcp.base.extend.*
import nbcp.base.model.HttpInvoke
import org.springframework.web.bind.annotation.*

@RestController
class DockerController {

    @PostMapping("/docker/restart/{name}")
    fun docker(@PathVariable("name") name: String) {
        api.sys.docker!!.killContainer(name);

        api.sys.docker!!.startContainer(name);
        if (HttpInvoke.lastRequest!!.result!!.status.IsInItems(204, 304) == false) {
            throw RuntimeException("启动 ${name} 失败, status:${HttpInvoke.lastRequest!!.result!!.status}")
            return
        }
    }


    @GetMapping("/docker/is-ready/{name}")
    fun ready(@PathVariable("name") name: String) {
        //6分钟， 每1.5秒执行一次。

        for (i in 1..240) {
            Thread.sleep(1500);
            var json = api.sys.docker!!.inspectContainer(name);
            var dockerStartAt = json.State.StartedAt.AsLocalDateTime();
            if (dockerStartAt == null) {
                continue;
            }

            if (json.State.Running == null) {
                continue;
            }

            return;
        }

        throw RuntimeException("已重新部署，但未检测到成功状态！");
    }


    @StopLog
    @GetMapping("/dockers-for-hosts")
    fun docker4Hosts(
        @RequestParam("excludes", required = false) excludes: String?
    ): String {

        var list = api.sys.docker!!.containers()
            .filter { container ->
                MyGatewayRouteRepository.apiTags.any { container.Image.contains(it, true) }
            }

        if (HttpInvoke.lastRequest!!.result!!.status.IfUntil(200, 300) == false) {
            throw RuntimeException("获取docker信息失败")
        }

        var excludeList = excludes.AsString().split(",").filter { it.HasValue }

        var ret = list
            .map {
                it.containerIp + " " + it.Names.sortedBy { it.length }
                    .first().remove("/")
            }

        if (excludeList.size > 0) {
            ret = ret.filterNot { n -> excludeList.any { n.contains(it) } }
        }

        return ret.joinToString("\n")
    }

    @PostMapping
    fun cleanImages(
        @RequestParam("name", required = false) name: String?
    ) {
        var setting = mor.dev.appDeploySetting.getAppDeploySetting()

//        api.sys.docker!!.images(setting.harborServer.host).forEach {
//            api.sys.docker!!.deleteImage(it.Id)
//        }
    }
}

